//                   _ooOoo_
//                  o8888888o
//                  88" . "88
//                  (| -_- |)
//                  O\  =  /O
//               ____/`---'\____
//             .'  \\|     |//  `.
//            /  \\|||  :  |||//  \
//           /  _||||| -:- |||||-  \
//           |   | \\\  -  /// |   |
//           | \_|  ''\---/''  |   |
//           \  .-\__  `-`  ___/-. /
//         ___`. .'  /--.--\  `. . __
//      ."" '<  `.___\_<|>_/___.'  >'"".
//     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
//     \  \ `-.   \_ __\ /__ _/   .-` /  /
//======`-.____`-.___\_____/___.-`____.-'======
//                   `=---='
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//            佛祖保佑       心想事成


package com.larissa.quiz;

import android.content.Context;
import androidx.room.Room;

import com.larissa.quiz.database.QuestionDao;
import com.larissa.quiz.database.QuestionDatabase;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class QuizRepository {
    private static final String DB_NAME="quiz_db";
    private static QuizRepository repository;
    private QuestionDao questionDao;
    private Executor executor= Executors.newSingleThreadExecutor();
    private List<Question> questions=new ArrayList<>();

    private QuizRepository(Context context){
        QuestionDatabase questionDB= Room.databaseBuilder(context,QuestionDatabase.class,DB_NAME).build();
        questionDao=questionDB.questionDao();
        executor.execute(() -> setQuestions(questionDao.getQuestions()));
    }

    public static QuizRepository getInstance(){
        if(repository==null)
            throw new IllegalStateException("QuizRepository must be initialized");
        return repository;
    }

    public static void initialize(Context context){
        if(repository==null)
            repository=new QuizRepository(context);
    }

    public List<Question> getQuestions(){
        return questions;
    }

    private void setQuestions(List<Question> questions){
        this.questions=questions;
    }

    public void addQuestion(Question question){
        executor.execute(() -> questionDao.addQuestion(question));
    }
}
